package MULE.Model.Logic;

import java.awt.event.ActionEvent;
import java.util.ArrayList;

import MULE.Model.Player;
import MULE.Model.Panel.GameConfigPanel;
import MULE.Model.Panel.TitlePanel;

/**
 * Logic module designed to manipulate the title panel and handle the title
 * panel's inputs.
 * 
 * @author jstep
 */
public class TitleLogic extends MulePresenter {

	public enum ActionCommand {
		NEW_GAME, LOAD_GAME;
	}

	/**
	 * Creates a new logic module designed to manipulate the title panel and
	 * handle the title panel's inputs.
	 * 
	 * @param titlePanel
	 *            The title panel this module listens to.
	 */
	public TitleLogic(TitlePanel view) {
		super(view);
		// Listen to the title panel's start button.
		((TitlePanel) view).addStartListener(this);
		((TitlePanel) view).addLoadListener(this);
	}

	/**
	 * Event handler. Responds to input from the TitlePanel.
	 * 
	 * @param e
	 *            The event which was fired on the title panel.
	 */
	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if (command.equals(ActionCommand.NEW_GAME.toString())) {
			showGameConfig();
		} else if (command.equals(ActionCommand.LOAD_GAME.toString())) {
			loadGame();
		}
	}

	/**
	 * Tells the application to show the game configuration panel.
	 */
	public void showGameConfig() {
		GameConfigPanel gameConfigPanel = new GameConfigPanel();
		GameConfigLogic gcl = new GameConfigLogic(gameConfigPanel);

		gcl.showView();
	}

	/**
	 * Load a game from file.
	 */
	public void loadGame() {
		// Get saved game name from user.
		String gameName = MuleDriver.showInputDialog("Load Game",
				"Enter the saved game's name:\n");
		String fileName = gameName + MuleDriver.SAVE_FILE_FORMAT;
		// Load game.
		if (MuleDriver.loadGame(fileName)) {
			MuleDriver.getGameLogic().showView();
			// Update score panel.
			ArrayList<Player> players = MuleDriver.getGame().getPlayers();
			for (Player p : players) {
				MuleDriver.updateScore(p);
			}
			MuleDriver.getGameLogic().resumeTurn();
		} else {
			// Could not load game.
			MuleDriver.showAlertDialog("Load Game",
					"Could not find game with specified name!");
		}
	}
}
